const { Op } = require('sequelize');
const Comment = require('../models/Comment');
const Novel = require('../models/Novel');
const Reader = require('../models/Reader');

exports.getComments = async (ctx) => {
  const { page = 1, size = 10, q = '' } = ctx.query;
  const offset = (page - 1) * size;

  try {
    const where = {};
    if (q) {
      where.content = { [Op.like]: `%${q}%` };
    }

    const { count, rows } = await Comment.findAndCountAll({
      where,
      include: [
        { model: Novel, as: 'novel', attributes: ['novel_name'] },
        { model: Reader, as: 'reader', attributes: ['username'] }
      ],
      limit: parseInt(size),
      offset: parseInt(offset),
      order: [['created_at', 'DESC']]
    });

    ctx.body = {
      content: rows,
      totalElements: count
    };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.likeComment = async (ctx) => {
  const { id } = ctx.params;
  try {
    const comment = await Comment.findByPk(id);
    if (!comment) {
      ctx.status = 404;
      ctx.body = { error: 'Comment not found' };
      return;
    }
    comment.likes += 1;
    await comment.save();
    ctx.body = comment;
  } catch (error) {
    ctx.status(400).send({ error: error.message });
  }
};

exports.getCommentsByNovelId = async (ctx) => {
  const { id } = ctx.params;
  try {
    const comments = await Comment.findAll({
      where: { novel_id: id },
      include: [{ model: Reader, as: 'reader', attributes: ['username', 'avatar'] }]
    });
    ctx.body = comments;
  } catch (error) {
    ctx.status(400).send({ error: error.message });
  }
};

exports.updateComment = async (ctx) => {
  const { id } = ctx.params;
  const { content } = ctx.request.body;
  const reader_id = ctx.state.user.id;
  const role = ctx.state.user.role;

  try {
    const comment = await Comment.findByPk(id);
    if (!comment) {
      ctx.status = 404;
      ctx.body = { error: 'Comment not found' };
      return;
    }

    if (comment.reader_id !== reader_id && role !== 'admin') {
      ctx.status = 403;
      ctx.body = { error: 'Forbidden' };
      return;
    }

    await comment.update({ content });
    ctx.body = comment;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.deleteComment = async (ctx) => {
  const { id } = ctx.params;
  const reader_id = ctx.state.user.id;
  const role = ctx.state.user.role;

  try {
    const comment = await Comment.findByPk(id);
    if (!comment) {
      ctx.status = 404;
      ctx.body = { error: 'Comment not found' };
      return;
    }

    if (comment.reader_id !== reader_id && role !== 'admin') {
      ctx.status = 403;
      ctx.body = { error: 'Forbidden' };
      return;
    }

    await comment.destroy();
    ctx.status = 204; // No Content
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};

exports.createComment = async (ctx) => {
  const { content } = ctx.request.body;
  const novel_id = ctx.params.id;
  const reader_id = ctx.state.user.id; // from JWT

  try {
    const comment = await Comment.create({
      content,
      novel_id,
      reader_id
    });
    ctx.status = 201;
    ctx.body = comment;
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};



exports.deleteComment = async (ctx) => {
  const { id } = ctx.params;
  try {
    const result = await Comment.destroy({ where: { comment_id: id } });
    if (result === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Comment not found' };
      return;
    }
    ctx.status = 204; // No Content
  } catch (error) {
    ctx.status = 400;
    ctx.body = { error: error.message };
  }
};
